package main

import (
	"encoding/gob"
	"fmt"
	"github.com/pkg/errors"
	_ "github.com/tim1020/godaemon"
	"logs"
	mon "monitor"
	"net"
	"strconv"
	. "tcpNetWorking/lib"
	"time"
)

type client struct {
	ip       string
	sendData ComplexData
}

func (c *client) GetThisIpAddr() string {
	var iplist []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				iplist = append(iplist, ipnet.IP.String())
			}
		}
	}
	index_ip := iplist[0]
	return index_ip
}

func (c *client) send() error {
	rw, err := Open(c.ip + Port)
	if err != nil {
		fmt.Println("客户端无法链接改地址：" + c.ip + Port)
		return err
	}
	n, err := rw.WriteString("string\n")
	if err != nil {
		return errors.Wrap(err, "Could not send the STRING request ("+strconv.Itoa(n)+" bytes written)")
	}
	n, err = rw.WriteString("Additional data.\n")
	if err != nil {
		return errors.Wrap(err, "Could not send additional STRING data ("+strconv.Itoa(n)+" bytes written)")
	}
	err = rw.Flush()
	if err != nil {
		return errors.Wrap(err, "Flush failed.")
	}

	// Read the reply.
	response, err := rw.ReadString('\n')
	if err != nil {
		return errors.Wrap(err, "Client: Failed to read the reply: '"+response+"'")
	}

	logs.PrintlnFile("STRING REQUEST : "+fmt.Sprint(response), 3)
	logs.PrintlnFile("Send a struct as GOB : Success", 3)
	if Debug {
		logs.PrintlnFile("Outer complexData struct : "+fmt.Sprint(c.sendData), 3)
	}

	enc := gob.NewEncoder(rw)
	n, err = rw.WriteString("gob\n")
	if err != nil {
		return errors.Wrap(err, "Could not write GOB data ("+strconv.Itoa(n)+" bytes written)")
	}
	err = enc.Encode(c.sendData)
	if err != nil {
		return errors.Wrapf(err, "Encode failed for struct: %#v", c.sendData)
	}
	err = rw.Flush()
	if err != nil {
		return errors.Wrap(err, "Flush failed.")
	}
	return nil
}

func main() {
	GetConfigInput("client")

	var com client
	com.ip = Addr
	for {
		com.sendData.NowTime = time.Now().Format("2006-01-02 15:04:05")
		com.sendData.Lan = LanName
		com.sendData.Ip = com.GetThisIpAddr()
		com.sendData.Host = mon.GetHostInformation()
		com.sendData.DiskInfo = mon.GetDiskInformation()
		com.sendData.DiskUsed = mon.GetDiskUsage(MonDir)
		com.sendData.CpuLoad = mon.GetCpuLoad()
		com.sendData.Memory = mon.GetMemoryInformation()
		com.sendData.Flow = mon.GetNetWorkFlow()
		com.sendData.NetWorkInfo = mon.GetNetWorkInformation()
		com.sendData.Process = mon.GetPids()
		com.sendData.CpuInfo = mon.GetCpuInformation()
		com.sendData.CpuUsed = mon.GetCpuUsed()
		err := com.send()
		if err != nil {
			fmt.Println("Error:", errors.WithStack(err))
		}

		time.Sleep(time.Second * time.Duration(Speed))
	}
}
